/**
 * Created by hcadmin on 16/10/26.
 */

//键盘收起时间监听
function packupKeyboard() {
    //用于撑高页面 便于滚动
    $(".extendHeight").css("height", "0vh");
    $(".need_keyboard").blur();
}



$(function(){
    //定义解析url方法
    (function ($) {
        $.getUrlParam = function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        }
    })(jQuery);


    //获取url上带的参数
    var dailyrecord_temp_id = $.getUrlParam('id');                      //日志模板 id
    //修改状态下有一下参数
    var dailyrecord_id = $.getUrlParam('dailyrecord_id');                 //日志id
    var edit = $.getUrlParam('edit');                                   //"edit"表示修改日志


    //返回按钮事件
    $("#log_back").on('click',function(){
        window.history.back(-1);
    });

    //渲染与取值

    //标题处理 是否必填记号
    function titleSet(field){
        var title = field.dailyrecord_temp_field_title;
        if (field.is_necessary == 1){
            //必填带上*
            title = title + "*";
        }
        return title;
    }

    //文本输入框渲染 模板类,值
    function drawTextInput(field,value){
        var title = titleSet(field);
        var textInput =
            "<div class='cell_box' >" +
                //标题
                "<div class='cell_title'>" + title + "</div>" +
                //输入框
                "<div contentEditable='true' class='cell_content_text need_keyboard' field_id='" + field.dailyrecord_temp_field_id + "' placeholder='请输入文字' is_necessary='"+field.is_necessary+"'>" + value + "</div>" +
                "<div style='clear: both;'></div>" +
            "</div>";

        $(".content_bigest").append(textInput);
    }

    //数字输入框渲染 模板类,值
    function drawNumInput(field,value){
        var title = titleSet(field);

        var numInput =
            "<div class='cell_box' >" +
                //标题
                "<div class='cell_title'>" + title + "</div>" +
                //输入框
                "<input type='number' class='cell_content_num need_keyboard' field_id='" + field.dailyrecord_temp_field_id + "' placeholder='请输入数字' value='" + value + "' is_necessary='"+field.is_necessary+"'>" +
               "<div style='clear: both;'></div>" +
            "</div>";

        $(".content_bigest").append(numInput);
    }

    //单选框渲染 模板类,值
    function drawSelect(field,value){
        var title = titleSet(field);
        //选项
        var options_string = field.options;

        var select_index = -1;
        if (value.length > 0){
            //有选项
            var options = [];
            options = options_string.split(",");
            select_index = options.indexOf(value);
        }

        var optionSelect =
            "<div class='cell_box'>" +
                //标题
                "<div class='cell_title'>" + title + "</div>" +
                //单选框
                "<div contentEditable='true' class='cell_content_select' field_id='" + field.dailyrecord_temp_field_id + "' placeholder='请选择' options='" + options_string + "' is_necessary='"+field.is_necessary+"' select_index='" + select_index + "'>" + value + "</div>" +
                "<div style='clear: both;'></div>" +
            "</div>";

        $(".content_bigest").append(optionSelect);
    }

    //时间选框渲染 模板类,值
    function drawTimeSelect(field,value){
        var title = titleSet(field);

        var formatter = "";
        var placeholder = "";
        var type = field.daiyrecord_temp_field_type;
        switch (type){
            case 3:
                formatter = "yyyy-MM-dd HH:mm";
                placeholder = "请选择日期";
                break;
            case 4:
                formatter = "yyyy-MM-dd";
                placeholder = "请选择日期";
                break;
            case 5:
                formatter = "HH:mm";
                placeholder = "请选择时间";
                break;
            default:
                break;
        }

        if (value.length > 0 && type != 5){
            value = timestampToString(parseInt(value),formatter);
        }

        var timeSelect =
            "<div class='cell_box' >" +
                //标题
                "<div class='cell_title'>" + title + "</div>" +
                //时间选框
                "<input readonly class='cell_content_time' field_id='" + field.dailyrecord_temp_field_id + "' value='" + value + "' placeholder='" + placeholder + "' formatter='" + formatter + "' is_necessary='"+field.is_necessary+"'>" +
                "<div style='clear: both;'></div>" +
            "</div>";

        $(".content_bigest").append(timeSelect);
    }

    //备注框渲染 模板类,值
    function drawNoteInput(field,value){
        var title = titleSet(field);
        var noteInput =
            "<div class='cell_box' >" +
                //标题
                "<div class='cell_title_note'>" + title + "</div>" +
                //输入框
                "<div contentEditable='true' class='cell_content_note need_keyboard' field_id='" + field.dailyrecord_temp_field_id + "' placeholder='请输入备注' is_necessary='"+field.is_necessary+"'>" + value + "</div>" +
            "</div>";

        $(".content_bigest").append(noteInput);
    }

    //高度调整
    function heightAdjust(){
        //数字输入框调整
        $(".cell_content_num").each(function(){
            calHeightAndPadding($(this));
        });
        //单选框调整
        $(".cell_content_select").each(function(){
            calHeightAndPadding($(this));
        });
        //时间选择器调整
        $(".cell_content_time").each(function(){
            calHeightAndPadding($(this));
        });
    }

    //具体计算方法
    function calHeightAndPadding(object){
        var system_height = $(window).height();
        //获得父级高度
        var parent_height = object.parent().height();
        //真是文本高
        var content_height = 0.03 * system_height;
        //计算垂直方向内边距
        var padding_y = (parent_height - content_height)/2;

        //object.css("height",parent_height - padding_y * 2 + "px");
        object.css("margin-top",padding_y + "px");
        object.css("margin-bottom",padding_y + "px");
    }

    //时间选择器绑定
    function timePickerBind(){
        $(".cell_content_time").each(function(){
            var formattet = $(this).attr("formatter");
            if (formattet == "yyyy-MM-dd HH:mm"){
                selectWhole($(this));
            }else if (formattet == "yyyy-MM-dd"){
                selectDate($(this));
            }else if (formattet == "HH:mm"){
                selectTime($(this));
            }
        })
    }

    //点击选择日期
    function selectDate(obj) {
        var currYear = (new Date()).getFullYear();
        var opt = {};
        opt.date = { preset: 'date' };
        opt.datetime = { preset: 'datetime' };
        opt.time = { preset: 'time' };
        opt.default = {
            theme: 'sense-ui', //皮肤样式
            display: 'modal', //显示方式
            mode: 'scroller', //日期选择模式
            lang: 'zh',
            startYear: currYear - 10, //开始年份
            endYear: currYear + 10 //结束年份

        };
        var optDateTime = $.extend(opt['date'], opt['default']);
        obj.mobiscroll(optDateTime).date(optDateTime);
    }
    function selectWhole(obj) {
        var currYear = (new Date()).getFullYear();
        var opt = {};
        opt.date = { preset: 'date' };
        opt.datetime = { preset: 'datetime' };
        opt.time = { preset: 'time' };
        opt.default = {
            theme: 'sense-ui', //皮肤样式
            display: 'modal', //显示方式
            mode: 'scroller', //日期选择模式
            lang: 'zh',
            startYear: currYear - 10, //开始年份
            endYear: currYear + 10 //结束年份
        };
        var optDateTime = $.extend(opt['datetime'], opt['default']);
        obj.mobiscroll(optDateTime).datetime(optDateTime);
    }
    function selectTime(obj) {
        var currYear = (new Date()).getFullYear();
        var opt = {};
        opt.date = { preset: 'date' };
        opt.datetime = { preset: 'datetime' };
        opt.time = { preset: 'time' };
        opt.default = {
            theme: 'sense-ui', //皮肤样式
            display: 'modal', //显示方式
            mode: 'scroller', //日期选择模式
            lang: 'zh',
            startYear: currYear - 10, //开始年份
            endYear: currYear + 10, //结束年份
            minDate: new Date()
        };
        var optTime = $.extend(opt['time'], opt['default']);
        obj.mobiscroll(optTime).time(optTime);
    }

    //单选框事件
    var current_selector;
    $(document).on('click','.cell_content_select',function(){
        current_selector = $(this);

        var options_string = HTMLEncode($(this).attr("options"));
        var options = options_string.split(",");

        $(".option_box").append("<div class='option_tip'>请选择</div>");
        $(".option_box").append("<div class='option_cell_box'></div>");

        var select_index = $(this).attr("select_index");

        for(var i = 0; i < options.length; i++){

            var img_src = "../../approval/approvalImg/unchoice_round.png";
            if (select_index != null && i == select_index){
                img_src = "../../approval/approvalImg/choice_round.png";
            }
            $(".option_cell_box").append(
                "<div class='option_cell' index='" + i + "'>" +
                    "<div class='option_content'>" + options[i] + "</div>" +
                    "<img class='option_select_img' src='" + img_src + "'>" +
                    "<div style='clear:both'></div>"+
                "</div>");

        }

        $(".option_box").append("<div><div class='cancel_select'>取消</div></div>");

        $(".call_back").show();
        //计算位置
        var system_height = $(window).height();
        var total_height = $(".option_box").height();
        var margin_top = (system_height - total_height)/2;
        $(".option_box").css("margin-top",margin_top + "px");
        //计算图标位置
        $(".option_select_img").each(function(){
            var icon_height = $(this).height();
            var parent_height = $(this).parent().height();

            var margin_top = (parent_height - icon_height)/2;
            $(this).css("margin-top",margin_top + "px");
        })

    });

    $(document).on('click','.option_cell',function(){
        //状态图片变化
        $(".option_select_img").attr("src","../../approval/approvalImg/unchoice_round.png");
        $(this).find(".option_select_img").attr("src","../../approval/approvalImg/choice_round.png");
        //获取值
        var select_val = $(this).find(".option_content").html();
        //展示
        $(current_selector).html(select_val);
        $(current_selector).attr("select_index",$(this).attr("index"));
        $(".option_box").empty();
        $(".call_back").hide();
    });

    //点击取消
    $(document).on('click','.cancel_select',function(){
        $(".option_box").empty();
        $(".call_back").hide();
    });

    //图片选择
    $(document).on('click','.img_icon',function(){
        $("#upload").click();
    });
    //图片上传
    $(document).on('change','#upload',function(){
        var formdata=new FormData($("#form")[0]);
        formdata.append("type","0");
        formdata.append("names", "img");
        var file = this.files[0];
        if (file != undefined){
            var file_name = file.name;
            var file_type = file.type;
            var type = file_type.split("/")[0];
            if(checkImageType(file_name)==true) {
                var lastImg;
                $.ajax({
                    beforeSend:function(){
                        var img_html = "<div class='img_delete_big'><img src='../../approval/approvalImg/loading.gif' class='img_real'><img src='../logImg/redDelete.png' class='red_delete'></div>";
                        img_html = "<div class='img_left_right'><div class='img_delete_big'><img src='../../approval/approvalImg/loading.gif' class='img_real'><img src='../logImg/redDelete.png' class='red_delete'></div></div>"
                        $(".img_icon").before(img_html);
                        lastImg = $(".img_delete_big .img_real").last();
                    },
                    type : 'POST',
                    url : apiurl+'/global/upload',
                    data: formdata,
                    cache : false,
                    processData : false,
                    contentType : false,
                    mimeType:"multipart/form-data",
                    success : function(d){
                        //console.log(d);
                        var data_url=JSON.parse(d).data;
                        lastImg.attr("src","http://"+data_url+"");

                        if($(".img_real").length>8){
                            $(".img_icon").hide();
                        }
                    }
                })
            }else {
                $(".call_back_success").html("不支持该图片类型!").fadeIn();
                setTimeout(function(){
                    $(".call_back_success").fadeOut(1000);
                },1000);
            }
        }
        var imgInput = $('#upload');
        imgInput.replaceWith(imgInput.val('').clone(true));
    });
    //图片删除
    $(document).on('click','.red_delete',function(){
        $(this).parent().remove();
        $(".img_icon").show();
    });

    //键盘事件
    $(document).on('focus','.need_keyboard',function(e){
        //debugger;

        //备注栏需要撑高
        if ($(this).hasClass("cell_content_note") == true) {
            $(".extendHeight").css("height", "10vh");
        }


        //文本框所在的div
        var nav_height = $("#log_navbar").outerHeight(true);

        var windowHeight = $(window).height();  //屏幕高度

        var current_top = $(document).scrollTop();

        var current_position_top = $(this).position().top;

        var distance_top = current_position_top - current_top;

        var keyboardHeight = windowHeight / 2;  //半屏

        var self_height = $(this).outerHeight(true);

        if (distance_top + self_height + keyboardHeight > windowHeight){
            //需要滚动
            var scroll_distance = distance_top + self_height + keyboardHeight - windowHeight;
            window.scrollTo(0, current_top + scroll_distance + nav_height);
        }
    });



    //失焦 恢复
    $(document).on('blur','.need_keyboard',function(e){
        $(".extendHeight").css("height", "0vh");
    });

    //数据加载
    var temp;
    if (edit == "edit"){
        $.ajax({
            beforeSend:function(){
                $(".loading").show();
                $(".show_hide").hide();
            },
            url:apiurl+"/dailyrecords/"+dailyrecord_id+"",
            type:"GET",
            data:{
                user_id:localStorage.user_id,
                token:localStorage.token
            },
            success:function(d){
                if(typeof d == "object"){
                    var msg= d.msg;
                    if(msg=="202") {
                        $(".token_iframe").fadeIn(1000);
                    }
                } else {
                    var call_back   = JSON.parse(d);
                    var data        = call_back.data;
                    var userInfo    = data.userCallbackString;

                    if (call_back.code == "0"){
                        $(".loading").hide();
                        $(".show_hide").show();
                        //基本数据加载
                        temp = data.dailyrecordTemp;
                        var dailyrecordTemp = data.dailyrecordTemp;
                        var dailyrecord_temp_title = dailyrecordTemp.dailyrecord_temp_title;
                        var fields= dailyrecordTemp.fieldValues;
                        var dailyrecord_img = data.dailyrecord_img;
                        var follows         = data.follows;
                        //日志标题
                        $('.log_title').html(dailyrecord_temp_title);
                        //模板内容添加
                        for(var i = 0;i < fields.length;i++){
                            var field = fields[i];
                            if (i == fields.length - 1){
                                //备注渲染
                                drawNoteInput(field,field.default_value);
                                continue;
                            }
                            switch (field.daiyrecord_temp_field_type){
                                case 0:
                                    drawTextInput(field,field.default_value);
                                    break;
                                case 1:
                                    drawNumInput(field,field.default_value);
                                    break;
                                case 2:
                                    drawSelect(field,field.default_value);
                                    break;
                                case 3:
                                    drawTimeSelect(field,field.default_value);
                                    break;
                                case 4:
                                    drawTimeSelect(field,field.default_value);
                                    break;
                                case 5:
                                    drawTimeSelect(field,field.default_value);
                                    break;
                                default:
                                    break;
                            }
                        }
                        //照片
                        var img_arr = dailyrecord_img.split(",");
                        if(img_arr!=""){
                            if(img_arr.length==9){
                                $(".img_icon").hide();
                            }
                            img_arr.reverse();
                            for(key in img_arr){
                                var img_html = "<div class='img_delete_big'><img src='"+img_arr[key]+"' class='img_real'><img src='../logImg/redDelete.png' class='red_delete'></div>";
                                $(".img_div_big").prepend(img_html);
                            }
                        }
                        //日志接收人
                        var follows_arr = follows.split(",");
                        if(follows_arr!=""){
                            for(key in follows_arr){
                                var name;
                                var avatar;
                                var id;
                                var qyxBindId;
                                for(var v=0;v<userInfo.length;v++){
                                    if(follows_arr[key]==userInfo[v].id){
                                        id    = userInfo[v].id;
                                        name  = userInfo[v].name;
                                        avatar= userInfo[v].avatar;
                                        qyxBindId = userInfo[v].qyxBindId;
                                    }
                                }
                                var img_src;
                                //if(avatar==""){
                                    var color = avatar_getColor(qyxBindId);
                                    img_src   = "<div class='cope_me_cover_div' style='background-color: "+color+"'>"+avatar_name(name)+"</div>";
                                //}else{
                                if (avatar.length > 0) {
                                    var src = avatar_getUrl(localStorage.user_id,localStorage.token,avatar);
                                    img_src += "<img src='"+src+"' class='cope_me_cover' hidden>";
                                }
                                contact_arr.push(id);
                                contact_avatar_arr.push(avatar);
                                contact_name_arr.push(name);
                                $("#copy_person").prepend("<div class='copy_me_person'>"+img_src+" <div class='cope_me_name' id='"+id+"' name='"+name+"' avatar='"+avatar+"'>"+name+"</div> </div>");
                            }
                        }
                        $("#add_copy_person").hide();
                        //去掉 点击头像可以删除
                        $('.p1').html("");

                        showAvatar(".cope_me_cover");
                        //高度调整
                        heightAdjust();
                        //时间绑定
                        timePickerBind();
                    }
                }
            }
        })
    }else {
        //新建 获取日志模板
        $.ajax({
            beforeSend:function(){
                //转菊花
                $(".loading").show();
                $(".show_hide").hide();
            },
            url:apiurl+"/dailyrecords/temp/"+dailyrecord_temp_id+"",
            type:"GET",
            success:function(d){
                //停止转菊花
                $(".loading").hide();
                $(".show_hide").show();
                temp = JSON.parse(d).data;
                var data = JSON.parse(d).data;
                var fields = data.fields;
                //右上角 选择模板
                $(".log_nav_right").html('选择模板').on('click',function(){
                    window.location.href='index.html';
                });
                for (var i = 0; i < fields.length; i++) {
                    var field = fields[i];
                    if (i == fields.length - 1){
                        //备注渲染
                        drawNoteInput(field,"");
                        continue;
                    }

                    switch (field.daiyrecord_temp_field_type){
                        case 0:
                            drawTextInput(field,"");
                            break;
                        case 1:
                            drawNumInput(field,"");
                            break;
                        case 2:
                            drawSelect(field,"");
                            break;
                        case 3:
                            drawTimeSelect(field,"");
                            break;
                        case 4:
                            drawTimeSelect(field,"");
                            break;
                        case 5:
                            drawTimeSelect(field,"");
                            break;
                        default:
                            break;
                    }
                }
                //高度调整
                heightAdjust();
                //时间绑定
                timePickerBind();
            }
        });
    }



    //取值
    function getTextInputValue(dailyrecord_temp_field_id){

        //console.log($(".cell_content_text[field_id='"+ dailyrecord_temp_field_id +"']").html());
        //console.log($(".cell_content_text[field_id='"+ dailyrecord_temp_field_id +"']").text());
        //debugger;

        return $(".cell_content_text[field_id='"+ dailyrecord_temp_field_id +"']").html();
    }
    function getNumInputValue(dailyrecord_temp_field_id){
        return $(".cell_content_num[field_id='"+ dailyrecord_temp_field_id +"']").val();
    }
    function getSelectValue(dailyrecord_temp_field_id){
        return $(".cell_content_select[field_id='"+ dailyrecord_temp_field_id +"']").html();
    }
    function getTimeSelectValue(dailyrecord_temp_field_id,daiyrecord_temp_field_type){
        var time_string = $(".cell_content_time[field_id='"+ dailyrecord_temp_field_id +"']").val();
        if (time_string.length == 0){
            return "";
        }
        if (daiyrecord_temp_field_type == 5){
            return time_string;
        }
        var timestamp = Date.parse(new Date(time_string));
        return timestamp;
    }
    function getNoteValue(dailyrecord_temp_field_id){
        return $(".cell_content_note[field_id='"+ dailyrecord_temp_field_id +"']").html();
    }


    function getValue(field){
        var default_value = "";
        switch (field.daiyrecord_temp_field_type){
            case 0:
                default_value = getTextInputValue(field.dailyrecord_temp_field_id);
                break;
            case 1:
                default_value = getNumInputValue(field.dailyrecord_temp_field_id);
                break;
            case 2:
                default_value = getSelectValue(field.dailyrecord_temp_field_id);
                break;
            case 3:
                default_value = getTimeSelectValue(field.dailyrecord_temp_field_id,field.daiyrecord_temp_field_type);
                break;
            case 4:
                default_value = getTimeSelectValue(field.dailyrecord_temp_field_id,field.daiyrecord_temp_field_type);
                break;
            case 5:
                default_value = getTimeSelectValue(field.dailyrecord_temp_field_id,field.daiyrecord_temp_field_type);
                break;
            default:
                break;
        }
        return default_value;
    }

    //提交日志
    $(".save_button").on('click',function(){
        //获取图片路径
        var dailyrecord_img_arr = [];
        var dailyrecord_img;
        if($(".img_real").length > 0){
            $(".img_real").each(function(index){
                dailyrecord_img_arr[index] = $(this).attr("src");
            });
            dailyrecord_img = dailyrecord_img_arr.join(",");
        }else{
            dailyrecord_img = "";
        }


        var fields;
        if (edit == "edit"){
            fields = temp.fieldValues;
        }else {
            fields = temp.fields;
        }

        var submit_fields = [];

        for (var i = 0; i < fields.length; i ++){
            var field = fields[i];
            var default_value = "";
            if (i == fields.length - 1){
                //直接备注取值
                default_value = getNoteValue(field.dailyrecord_temp_field_id);
            }else {
                default_value = getValue(field);
            }

            if (field.is_necessary == 1 && default_value.length == 0){
                //提示未填
                $('.system_message').html("" + field.dailyrecord_temp_field_title + "不能为空").show().fadeOut(2000);
                return;
            }

            submit_fields[i] = {
                dailyrecord_temp_field_id:field.dailyrecord_temp_field_id,
                default_value:default_value
            };

        }
        //debugger;
        //获取抄送人的id
        var follows_arr = [];
        var follows = "";
        if($(".cope_me_name").length>0){
            $(".cope_me_name").each(function(index){
                follows_arr[index] = $(this).attr("id");
            });
            follows = follows_arr.join(",");
        }else{
            $('.system_message').html('接收人不能为空').show().fadeOut(2000);
            return;
        }
        //alert(localStorage.user_name);
        var data={
            dailyrecord_temp_id:dailyrecord_temp_id,
            user_id:localStorage.user_id,
            user_name:decodeURI(localStorage.user_name),
            group_id:localStorage.group_id,
            dailyrecord_img:dailyrecord_img,
            follows:follows,
            fields:submit_fields
        };
        //debugger;
        var data_json = JSON.stringify(data);
        //debugger;
        $.ajax({
            beforeSend:function(){
                $(".system_message").html("正在提交...").show();
                $(".save_button").attr("disabled","true");
            },
            url:apiurl+"/dailyrecords",
            type:"POST",
            data:{
                jsonString:data_json,
                userId:localStorage.user_id,
                token:localStorage.token,
                imtoken:localStorage.imToken,
                qyxBindId:localStorage.qyxBindId,
                title:localStorage.user_name+"发布了一个新的日志:"+temp.dailyrecord_temp_title
            },
            success:function(d){
                $(".save_button").html("提交");
                var data = JSON.parse(d);
                if(data.code=="0"){
                    var dailyrecord_id = "";
                    dailyrecord_id = data.data;
                    $(".system_message").fadeOut(2000).html("提交成功").show().fadeOut(2000,function(){
                        window.location.href="logDetail.html?index=0&id="+dailyrecord_id+"";
                    });
                }else{
                    $(".system_message").fadeOut(2000).html(data.msg).show().fadeOut(2000);
                }
            }
        });
    });


    //联系人选择
    var teamName            = "";
    //联系人全局
    var contact_arr         = [];
    var contact_name_arr    = [];
    var contact_avatar_arr  = [];
    var contact_qyxBindId_arr=[];

    var temp_arr            = [];
    var temp_name_arr       = [];
    var temp_avatar_arr     = [];
    var temp_qyxBindId_arr  = [];
    //获取团队列表
    getTeamName();

    var top = 0;
    //联系人列表
    $(document).on('click','#add_copy_person',function(){

        top = $(document).scrollTop();

        $(".model_div").hide();
        $(".contact_div").show();
        initpart();
    });
    //-----点击头像删除此人
    $(document).on('click','.cope_me_cover',function(){
        if(edit!="edit"){
            $(this).parent().remove();
            var id      = $(this).parent().children(":last-child").attr("id");
            var name    = $(this).next().attr("name");
            var avatar  = $(this).next().attr("avatar");

            for(key in contact_arr){
                if(contact_arr[key]==id){
                    contact_arr.splice(key,1);
                    contact_name_arr.splice(key,1);
                    contact_avatar_arr.splice(key,1);
                    contact_qyxBindId_arr.splice(key,1);
                }
            }
        }else{
            $(".call_back_success").html("修改日志无法删除接收人").show().fadeOut(2000);
        }

    });
    $(document).on('click','.cope_me_cover_div',function(){
        if(edit!="edit"){
            $(this).parent().remove();
            var id      = $(this).parent().children(":last-child").attr("id");
            var name    = $(this).next().attr("name");
            var avatar  = $(this).next().attr("avatar");

            for(key in contact_arr){
                if(contact_arr[key]==id){
                    contact_arr.splice(key,1);
                    contact_name_arr.splice(key,1);
                    contact_avatar_arr.splice(key,1);
                    contact_qyxBindId_arr.splice(key,1);
                }
            }
        }else{
            $(".call_back_success").html("修改日志无法删除接收人").show().fadeOut(2000);
        }
    });

    $(".contact_back").on('click',function(){
        removeSomeThing();

        for(a1 in temp_arr){
            for(a in contact_arr){
                if(contact_arr[a]==temp_arr[a1]){
                    contact_arr.splice(a,1);
                    contact_name_arr.splice(a,1);
                    contact_avatar_arr.splice(a,1);
                    contact_qyxBindId_arr.splice(a,1)
                }
            }
        }

        temp_arr=[];
        temp_name_arr=[];
        temp_avatar_arr=[];
        temp_qyxBindId_arr=[];
    });
    //加载部门列表 已经默认成员列表  顺便获取用户所在部门的名称

    function getTeamName(){
        var url_c  = tk_apiurl+"contacteam/findone";
        var data = {"userId":user_id,"token":token,"data":JSON.stringify({'id':group_id})};
        $.ajax({
            async: false,
            crossDomain: true,
            url: url_c,
            method: "POST",
            data:data,
            jsonpCallback:"jsoncallback",
            dataType: "jsonp",
            success:function(d) {
                var data1 = '';
                var status = '';

                data = eval('(' + d + ')');
                status = data.statusCode;
                if (data.result) {
                    data = eval('(' + data.result + ')');
                }
                teamName = data.teamName;
            }
        });
    }

    function initpart(){
        var url_c  = tk_apiurl+"contacteam/mydepts";
        var data = {"userId":user_id,"token":token,"data":JSON.stringify({'teamId':group_id,'parentId':"0"})};
        $.ajax({
            beforeSend:function(){
                $(".loading_c").show();
                $(".contact_bigest").hide();
            },
            async: true,
            crossDomain: true,
            url: url_c,
            method: "POST",
            data:data,
            jsonpCallback:"jsoncallback",
            dataType: "jsonp",
            success:function(d){

                var data='';
                var data1='';
                var status='';

                data = eval('('+d+')');
                status = data.statusCode;
                if(data.result){
                    data1 = eval('(' + data.result + ')');
                }
                if(status==202){
                    $(".token_iframe").fadeIn(1000);
                }
                else {
                    $(".loading_c").hide();
                    //title
                    $(".contact_title").html(teamName);
                    //contact_bigest添加名称条
                    //var contact_name_html = "<div class='group_name_div'>"+teamName+"<img src='../../approval/approvalImg/contact.png' class='group_img'></div>";
                    var contact_name_html = "<div class='group_name_div'>"+teamName+"</div>";
                    $(".contact_bigest").show().prepend(contact_name_html);
                    //$(".contact_bigest").show();
                    //加载部门
                    var team = data1.depts;
                    var html="";
                    for(var i=0;i<team.length;i++){
                        html += "<div class='team_bigest' id='"+team[i].id+"'>" +
                            "<div class='team_mid' is_choice='0'>" +
                            "<div class='team_left'>" +
                            //"<img src='../../approval/approvalImg/team.png' class='team_pic'>" +
                            "<div class='team_name'>"+team[i].departmentName+"</div>" +
                            "</div>" +
                            "<div class='team_right'>" +
                            "<img src='../../log/logImg/rightIcon.png' class='right_icon'></div></div>" +
                            "</div>";
                    }

                    //加载默认的用户
                    var users = data1.users;
                    var html_users="";

                    for(var a=0;a<users.length;a++){
                        var _choice = "0";
                        var _img    = "<img src='../../task/images/task/circleCheckBoxUnselect.png' class='round_tick'>";

                        for(var j=0;j<contact_arr.length;j++){
                            if(contact_arr[j]==users[a].userId){
                                _choice = "1";
                                _img    = "<img src='../../task/images/task/circleCheckBoxSelect.png' class='round_tick'>";
                            }
                        }
                        var img_url;
                        var avatar1 = users[a].avatar;
                        var qyxBindId = users[a].userIM;
                        var name = users[a].userName;

                        //if(avatar1==""){
                            var color = avatar_getColor(qyxBindId);
                            img_url = "<div class='user_pic_div' style='background-color: "+color+"'>"+avatar_name(name)+"</div>"
                        //}else{
                        if (avatar1.length > 0) {
                            var src = avatar_getUrl(localStorage.user_id,localStorage.token,avatar1);
                            img_url += "<img src='"+src+"' class='user_pic' hidden>";
                        }

                        html_users +="<div class='user_mid' id='"+users[a].userId+"' qyxBindId='"+qyxBindId+"' name='"+users[a].userName+"' avatar='"+users[a].avatar+"' is_choice='"+_choice+"'>" +
                            "<div class='choice_it_div'>"+_img+"</div>" +
                            "<div class='user_left'>" +
                            ""+img_url+"" +
                            "<div class='user_name'>"+users[a].userName+"</div>" +
                            "</div>" +
                            "</div>";
                    }
                    $(".team_content_bigest").append(html);
                    $(".contact_content").append(html_users);
                    showAvatar(".user_pic");
                    //最后一个部门的border-bottom隐藏
                    $(".team_mid").each(function(){
                        $(this).last().css('borderBottom','0px');
                    });
                }
            }
        });
    }
    //点击行获取部门下的成员列表
    var _team;
    $(document).on('click','.team_mid',function(){
        $(this).css("borderBottom","1px solid #e5e5e5");
        _team = $(this).parent();
        var is_choice = $(this).attr("is_choice");
        if(is_choice=="0"){
            $(this).find(".right_icon").addClass('right_icon_down').attr('src','../../task/images/task/arrow.png');
            var deptId = $(_team).attr("id");
            var url    = tk_apiurl+"contacteam/mydeptsall";
            var data   = {"userId":user_id,"token":token,"data":JSON.stringify({'teamId':group_id,'deptId':deptId})};
            $.ajax({
                async: true,
                crossDomain: true,
                url: url,
                method: "POST",
                data:data,
                jsonpCallback:"jsoncallback",
                dataType: "jsonp",
                success:function(d){

                    var data='';
                    var data1='';
                    var status='';

                    data = eval('('+d+')');
                    status = data.statusCode;
                    if(data.result){
                        data1 = eval('(' + data.result + ')');
                    }
                    if(status==202){
                        $(".token_iframe").fadeIn(1000);
                    }
                    else {
                        var users = data1.users;

                        var html="";

                        for(var i=0;i<users.length;i++){
                            var _choice = "0";
                            var _img    = "<img src='../../task/images/task/circleCheckBoxUnselect.png' class='round_tick'>";

                            for(var j=0;j<contact_arr.length;j++){
                                if(contact_arr[j]==users[i].userId){
                                    _choice = "1";
                                    _img    = "<img src='../../task/images/task/circleCheckBoxSelect.png' class='round_tick'>";
                                }
                            }
                            var img_url;
                            var avatar1 = users[i].avatar;
                            var qyxBindId = users[i].userIM;
                            var name = users[i].userName;
                            //if(avatar1==""){
                                var color = avatar_getColor(qyxBindId);
                                img_url = "<div class='user_pic_div' style='background-color: "+color+"'>"+avatar_name(name)+"</div>"
                            //}else{
                            if (avatar1.length > 0) {
                                var src = avatar_getUrl(localStorage.user_id,localStorage.token,avatar1);
                                img_url += "<img src='"+src+"' class='user_pic' hidden>";
                            }
                            html +="<div class='user_mid' id='"+users[i].userId+"' qyxBindId='"+qyxBindId+"' name='"+name+"' avatar='"+avatar1+"' is_choice='"+_choice+"'>" +
                                "<div class='choice_it_div'>"+_img+"</div>" +
                                "<div class='user_left'>" +
                                ""+img_url+"" +
                                "<div class='user_name'>"+users[i].userName+"</div>" +
                                "</div>" +
                                "</div>";
                        }
                        $(_team).append(html);

                        $(".user_mid").last().css("border","none");
                        showAvatar(".user_pic");
                    }

                }
            });
            $(this).attr("is_choice","1");
        }else{
            $(".right_icon").removeClass('right_icon_down').attr('src','../../log/logImg/rightIcon.png');
            $(this).nextAll().hide();
            $(this).attr("is_choice","0");
        }
    });

    //选择联系人
    $(document).on('click','.user_mid',function(){
        var id        = $(this).attr('id');
        var name      = $(this).attr('name');
        var avatar    = $(this).attr('avatar');
        var is_choice = $(this).attr("is_choice");
        var qyxBindId = $(this).attr("qyxBindId");

        if(is_choice=="0"){
            contact_arr.push(id);
            contact_name_arr.push(name);
            contact_avatar_arr.push(avatar);
            contact_qyxBindId_arr.push(qyxBindId);
            temp_arr.push(id);
            temp_name_arr.push(name);
            temp_avatar_arr.push(avatar);
            temp_qyxBindId_arr.push(qyxBindId);
        }else{
            for(key in contact_arr){
                if(contact_arr[key]==id){
                    contact_arr.splice(key,1);
                    contact_name_arr.splice(key,1);
                    contact_avatar_arr.splice(key,1);
                    contact_qyxBindId_arr.splice(key,1);
                }
            }

            for(key in temp_arr){
                if(temp_arr[key]==id){
                    temp_arr.splice(key,1);
                    temp_name_arr.splice(key,1);
                    temp_avatar_arr.splice(key,1);
                    temp_qyxBindId_arr.splice(key,1);
                }
            }

        }

        $('.user_mid').each(function(){
            var ids = $(this).attr('id');
            if(ids==id){
                if(is_choice=="0"){
                    //console.log($($(this).find('.round_tick')).attr('src'));
                    $($(this).find('.round_tick')).attr('src','../../task/images/task/circleCheckBoxSelect.png');
                    $(this).attr("is_choice","1");
                }else{
                    $(this).find('.round_tick').attr('src','../../task/images/task/circleCheckBoxUnselect.png');
                    $(this).attr("is_choice","0");
                }
            }
        })
    });

    //点击确定
    $(".contact_choice").on('click',function(){
        removeSomeThing();

        $(".copy_me_person").remove();
            for(var i=0,j= 0,z= 0,x=0;i<contact_arr.length,j<contact_name_arr.length,z<contact_avatar_arr.length,x<contact_qyxBindId_arr.length;i++,j++,z++,x++){
                var img_src;
                //if(contact_avatar_arr[z]==""){
                    var color = avatar_getColor(contact_qyxBindId_arr[x]);
                    img_src   = "<div class='cope_me_cover_div' style='background-color: "+color+"'>"+avatar_name(contact_name_arr[j])+"</div>";
                //}else{
                if (contact_avatar_arr[z].length > 0){
                    var src = avatar_getUrl(localStorage.user_id,localStorage.token,contact_avatar_arr[z]);
                    img_src += "<img src='"+src+"' class='cope_me_cover' hidden>";
                }
                $("#copy_person").prepend("<div class='copy_me_person'>"+img_src+"<div class='cope_me_name' id='"+contact_arr[i]+"' name='"+contact_name_arr[j]+"' avatar='"+contact_avatar_arr[z]+"'>"+contact_name_arr[j]+"</div></div>");
            }

        var height = 0;

        $(".copy_me_person").each(function(){
            var current_height = $(this).height();
            if (current_height > height){
                height = current_height;
            }
        });

        $(".copy_me_person").each(function(){
            $(this).height(height);
        });

        temp_arr=[];
        temp_name_arr=[];
        temp_avatar_arr=[];
        temp_qyxBindId_arr=[];

        showAvatar(".cope_me_cover");

        //坐标归位
        window.scrollTo(0,top);
        top = 0;
    });
    //remove hide show
    function removeSomeThing(){
        $(".contact_div").hide();
        $(".model_div").show();
        $(".team_bigest").remove();
        $(".user_mid").remove();
        $(".group_name_div").remove();
    }

    function showAvatar(classname){
        $(classname).one("load",function(){
            $(this).show();
            $(this).prev().hide();
        });
    }
});